package webs;

import dao.pojo.Users;
import domain.ApplicationContext;
import domain.UserFacade;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: winstars
 * Date: 2007-2-28
 * Time: 15:34:47
 * To change this template use File | Settings | File Templates.
 */
public class Login extends HttpServlet {
	
	private UserFacade userService;

    @Override
    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        doPost(httpServletRequest,httpServletResponse);
    }

    @Override
    protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
            //To change body of overridden methods use File | Settings | File Templates.
    	httpServletRequest.setCharacterEncoding("UTF-8");
    	userService=(UserFacade)ApplicationContext.get("UserService");
    	String username = httpServletRequest.getParameter("UserName");
    	String password = httpServletRequest.getParameter("PassWord");
    	Users loginuser = new Users();
    	loginuser.setUserName(username);
    	loginuser.setPassword(password);
    	Users dbuser = userService.login(loginuser);
    	if((dbuser!=null)&&dbuser.getPassword().equals(password)) 
    	  {
    		HttpSession session = httpServletRequest.getSession();
  		    session.setAttribute("login_user", dbuser);
  		    if(dbuser.getType().getId().intValue()==2)
  		    	httpServletResponse.sendRedirect("Manager.jsp");
  		    else
    		    httpServletResponse.sendRedirect("LoginSucceed");
    		}
    	else httpServletResponse.sendRedirect("LoginError");
    	
    }

    @Override
    public void destroy() {
        super.destroy();    //To change body of overridden methods use File | Settings | File Templates.
    }

    @Override
    public void init() throws ServletException {
        super.init();    //To change body of overridden methods use File | Settings | File Templates.
    }

	public UserFacade getUserFacade() {
		return userService;
	}

	public void setUserFacade(UserFacade userFacade) {
		this.userService = userFacade;
	}
}
